package netty.test9nettySimple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    //1，通道就绪时触发（就可以发消息了）
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //super.channelActive(ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,服务器 miao", CharsetUtil.UTF_8));
    }
    //2,当通道有读取事件时触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //super.channelRead(ctx, msg);
        ByteBuf buf=(ByteBuf)msg;
        System.out.println("客户端收到服务器回复的消息："+buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址为："+ctx.channel().remoteAddress());
    }

    //3,异常发生后，关闭通道


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        System.out.println("服务器断开连接");
        ctx.channel().close();//也可以用 ctx.close()
    }
}
